package com.lemon.funplus;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lemon.funplus.object.DetailsCateObject;
import com.lemon.funplus.object.HomeObject;
import com.lemon.funplus.parse.JsonParser;
import com.lemon.funplus.ulti.BaseEngine;

public class DetailsTruyenActivity extends Activity {
	public static String ITEM_KEY = "trans_item";

	private WebView webViewFB = null;
	private WebView childWebView = null;
	private LinearLayout parentLayout;
	ImageView imageView;
	TextView textView;
	HomeObject homeObject;
	ProgressBar loadingProgressBar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.details_truyen_layout);
		getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
		this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
		Bundle extras = getIntent().getExtras();
		if (getIntent().hasExtra(ITEM_KEY))
			homeObject = (HomeObject) extras.getSerializable(ITEM_KEY);
		imageView = (ImageView) findViewById(R.id.actionbar_imageDrawer);
		textView = (TextView) findViewById(R.id.textViewTitle);
		loadingProgressBar = (ProgressBar) findViewById(R.id.progressBar_loadding);

		webViewFB = new WebView(this);
		webViewFB.setWebViewClient(new FaceBookClient());
		webViewFB.setWebChromeClient(new FBChromeClient());
		parentLayout = (LinearLayout) findViewById(R.id.parentLayout);

		webViewFB.setLayoutParams(getLayoutParams());

		final WebSettings webSettings = webViewFB.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setSupportMultipleWindows(true);
		webSettings.setTextSize(WebSettings.TextSize.NORMAL);
		webViewFB.setWebViewClient(new WebViewClient() {
			public void onPageFinished(WebView view, String url) {
				loadingProgressBar.setVisibility(View.GONE);
			}
		});
		parentLayout.addView(webViewFB);

		if (homeObject != null) {
			textView.setText(homeObject.gettitle());
			new DetailsAsync().execute("");
		}
		imageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
	}

	private String getHTMLData(String content, String newsURL) {

		StringBuffer sb = new StringBuffer();
		sb.append("<html>");
		sb.append("<head>");
		sb.append("<style>img{max-width: 100%; width:auto; height: auto;}</style>");
		// sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
		// sb.append("<meta name=\"viewport\" content=\"user-scalable=yes, initial-scale=1.0, width=device-width\">");
		// sb.append("<style>html,body{width:100%;height:100%;margin:0;padding:5px;}#my-image{width:100%;margin:0;padding:5px;}</style>");
		sb.append("<title>Funplus.vn</title>");
		sb.append("</head>");
		sb.append("<body>");
		// sb.append("<h1>Anggota TNI ikut demo untuk beri rasa aman</h1>");
		// sb.append("<h1>Comment facebook</h1>");
		sb.append("" + content + "");
		sb.append("<div class=\"fb-comments\" data-href=\"" + newsURL + "\" data-num-posts=\"5\" data-width=\"680\"></div>");
		sb.append("<div id=\"fb-root\"></div>");
		sb.append("<script>(function(d, s, id) {");
		sb.append("var js, fjs = d.getElementsByTagName(s)[0];");
		sb.append("if (d.getElementById(id)) {return;}");
		sb.append("js = d.createElement(s); js.id = id;");
		sb.append("js.src = \"//connect.facebook.net/en_US/all.js#xfbml=1&appId=1375226042786650\";");
		sb.append("fjs.parentNode.insertBefore(js, fjs);");
		sb.append("}(document, 'script', 'facebook-jssdk'));");
		sb.append("</script>");
		sb.append("</body>");
		sb.append("</html>");

		return sb.toString();
	}

	private LinearLayout.LayoutParams getLayoutParams() {
		return new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
	}

	private class FaceBookClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.i("REQUEST URL", url);
			return false;
		}
	}

	final class FBChromeClient extends WebChromeClient {

		@Override
		public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
			childWebView = new WebView(DetailsTruyenActivity.this);
			childWebView.getSettings().setJavaScriptEnabled(true);
			childWebView.getSettings().setSupportZoom(true);
			childWebView.getSettings().setBuiltInZoomControls(true);
			childWebView.setWebViewClient(new FaceBookClient());
			childWebView.setWebChromeClient(this);
			childWebView.setLayoutParams(DetailsTruyenActivity.this.getLayoutParams());

			parentLayout.addView(childWebView);

			childWebView.requestFocus();
			webViewFB.setVisibility(View.GONE);
			WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
			transport.setWebView(childWebView);
			resultMsg.sendToTarget();
			return true;
		}

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			DetailsTruyenActivity.this.setProgress(newProgress * 100);
		}

		@Override
		public void onCloseWindow(WebView window) {
			parentLayout.removeViewAt(parentLayout.getChildCount() - 1);
			childWebView = null;
			webViewFB.setVisibility(View.VISIBLE);
			webViewFB.requestFocus();
		}

	}

	public class DetailsAsync extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... arg0) {
			String str = JsonParser.detailsItem(homeObject.getid());
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
//			BaseEngine.showLogformLongString("", result);
			if (result != null)
				try {
					DetailsCateObject cateObject = JsonParser.readDetails(result);
					String content = "";
					if (cateObject != null) {
						content = cateObject.getcontent();
						// Html.fromHtml(cateObject.getcontent()).toString();
						content = content.replace("; width:", "; ");
						content = content.replace("<pre>", "");
						content = content.replace("<img", "<img style=\"width:100%!important\"");
					}

					webViewFB.loadDataWithBaseURL("http://funplus.vn/", getHTMLData(content, cateObject.getfbcomment()), "text/html", "utf-8", null);
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
	}

}
